package com.nbsaas.boot.controller.lock;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.ConcurrentHashMap;

public class ReentrantLockService implements LockService {

    private final ConcurrentHashMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean lock(String key) {
        ReentrantLock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        lock.lock();
        return true;
    }

    @Override
    public boolean unlock(String key) {
        ReentrantLock lock = lockMap.get(key);
        if (lock != null) {
            lock.unlock();
            return true;
        }
        return false;
    }

    @Override
    public boolean isLocked(String key) {
        ReentrantLock lock = lockMap.get(key);
        return lock != null && lock.isLocked();
    }
}
